package com.dagene.weixin.util;

import net.sf.json.JSONObject;

import com.dagene.weixin.bean.AccessToken;
import com.dagene.weixin.bean.ImageMsg;
import com.dagene.weixin.bean.MediaContent;
import com.dagene.weixin.bean.TextContent;
import com.dagene.weixin.bean.TextMsg;
import com.dagene.weixin.bean.VoiceMsg;

/**
 * 公众号给用户发送信息
 * 
 * @author wangjl
 * 
 */
public class PushUtil {
	HttpUtil httpUtil = new HttpUtil();
	String httputilUrl;

	public PushUtil() {

		AccessToken at = httpUtil.getAccessToken(Constants.APPID,
				Constants.APPSECRET);
		httputilUrl = "https://api.weixin.qq.com/cgi-bin/message/custom/send?access_token=ACCESS_TOKEN";
		// 每次发送7条
		httputilUrl = httputilUrl.replace("ACCESS_TOKEN", at.getToken());
	}

	public JSONObject sendResponse(String touser, String msg) {
		TextMsg message = new TextMsg();
		message.setTouser(touser);
		message.setMsgtype(MessageUtil.REQ_MESSAGE_TYPE_TEXT);
		TextContent tc = new TextContent();
		tc.setContent(msg);
		message.setText(tc);
		JSONObject json = JSONObject.fromObject(message);
		return httpUtil.httpPostRequest(httputilUrl, "", json.toString());
	}

	public void sendResponseImg(String touser, String msg) {
		ImageMsg message = new ImageMsg();
		message.setTouser(touser);
		message.setMsgtype(MessageUtil.REQ_MESSAGE_TYPE_IMAGE);
		MediaContent mc = new MediaContent();
		mc.setMedia_id(msg);
		message.setImage(mc);
		JSONObject json = JSONObject.fromObject(message);
		httpUtil.httpPostRequest(httputilUrl, "", json.toString());
	}

	public void sendResponseVoice(String touser, String msg) {
		VoiceMsg message = new VoiceMsg();
		message.setTouser(touser);
		message.setMsgtype(MessageUtil.REQ_MESSAGE_TYPE_VOICE);
		MediaContent mc = new MediaContent();
		mc.setMedia_id(msg);
		message.setVoice(mc);
		JSONObject json = JSONObject.fromObject(message);
		httpUtil.httpPostRequest(httputilUrl, "", json.toString());
	}

	public void sendMediaResponse(String touser, String mediaId) {

		// image类型
		ImageMsg message = new ImageMsg();
		message.setTouser(touser);
		message.setMsgtype(MessageUtil.REQ_MESSAGE_TYPE_IMAGE);
		MediaContent mc = new MediaContent();
		mc.setMedia_id(mediaId);
		message.setImage(mc);
		JSONObject json = JSONObject.fromObject(message);
		httpUtil.httpPostRequest(httputilUrl, "", json.toString());
	}

}
